package com.example.Config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    //ShiroFilterFactoryBean 第三步
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);

        //添加shiro内置过滤器
        /*
           anno:无需认证即可访问
           authc：必须认证才能访问
           user：必须记住了才能访问
           perms：拥有对某个资源的权限才能访问
           role：拥有某个角色权限才能访问
        */
        Map<String, String> filterMap = new LinkedHashMap<>();
        //拦截
        /*filterMap.put("/user/addUser","authc");
        filterMap.put("/user/updataUser","authc");*/

        //未授权的用户会跳到请求授权界面，perms在authc前
        filterMap.put("/user/addUser","perms[user:addUser]");
        filterMap.put("/user/updataUser","perms[user:updataUser]");

        //支持通配符
        filterMap.put("/user/*","authc");



        bean.setFilterChainDefinitionMap(filterMap);

        //被拦截的页面跳转到登录页面
        bean.setLoginUrl("/to_login");
        //登录成功后跳转的链接
        bean.setSuccessUrl("/index");
        //未授权的请求
        bean.setUnauthorizedUrl("/Unauthorized");
        return bean;
    }

    //DefaultSecurityManager  第二步
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);

        return securityManager;
    }

    //创建一个UserRealm对象，需要自定义 第一步
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
    //整合shiro——thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
